const APPLICATIONID = '**************'
const RESTAPIKEY = '********************'


function filterStatus(res) {
  if (res.status / 100 === 2) {
    return res
  }
  return res
  // const error = new Error()
  // error.res = res
  // throw error
}

function filterJSON(res) {
  return res.json()
}

//url后缀加上id例如：查找GameScore表里面id为e1kXT22L的数据->https://api.bmob.cn/1/classes/GameScore/e1kXT22L

//获取一行数据
export async function get(url) {
  const uri = encodeURI(url)
  return fetch(uri, {
    method: 'GET',
    headers: {
      'X-Bmob-Application-Id': APPLICATIONID,
      'X-Bmob-REST-API-Key': RESTAPIKEY,
      Accept: 'application/json',
      'Content-Type': 'application/json'
    }
  }).then(filterStatus).then(filterJSON).catch(error => console.log('test error', error))
}

export async function whereGet(url, body) {
  const uri = encodeURI(url)
  return fetch(url, {
    method: 'GET',
    headers: {
      'X-Bmob-Application-Id': APPLICATIONID,
      'X-Bmob-REST-API-Key': RESTAPIKEY,
      Accept: 'application/json',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(body)
  }).then(filterStatus).then(filterJSON).catch(error => console.log('test error', error))
}

//修改一行数据
export async function puts(url, body) {
  const uri = encodeURI(url)
  return fetch(uri, {
    method: 'PUT',
    headers: {
      'X-Bmob-Application-Id': APPLICATIONID,
      'X-Bmob-REST-API-Key': RESTAPIKEY,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(body)
  }).then(filterStatus).then(filterJSON).catch(error => console.log('修改数据出错啦！！！', error))
}

//删除一条
//url后缀加上删除数据的ID拼成新的url
export async function deletes(url) {
  const uri = encodeURI(url)
  return fetch(uri, {
    method: 'DELETE',
    headers: {
      'X-Bmob-Application-Id': APPLICATIONID,
      'X-Bmob-REST-API-Key': RESTAPIKEY
    }
  }).then(filterStatus).then(filterJSON).catch(error => console.log('删除数据出错啦！！！', error))
}


export async function post(url, body) {
  const uri = encodeURI(url)
  return fetch(uri, {
    method: 'POST',
    headers: {
      'X-Bmob-Application-Id': APPLICATIONID,
      'X-Bmob-REST-API-Key': RESTAPIKEY,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(body)
  }).then(filterStatus).then(filterJSON).catch(error => console.log('test error', error))
}


export async function postFile(url, params) {
  const uri = encodeURI(url)
  return fetch(uri, {
    method: 'POST',
    headers: {
      'X-Bmob-Application-Id': APPLICATIONID,
      'X-Bmob-REST-API-Key': RESTAPIKEY
    },
    body: JSON.stringify(params)
  }).then(filterStatus).then(filterJSON).catch(error => console.log('test error', error))
}
